import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector, history } from 'umi';
import Header from '@/components/Header/Header';
import { Mask, RadioGroup, Radio, Message } from '@/design';
import { queryInvoice } from '@/services/order'
import { isEmpty } from '@/utils/common';
// import LoveCode from './LoveCode';
import styles from './checkorder.less';
import LoveCodeModal from './compoments/loveCodeModal';

export default function () {

  const { payhold } = useSelector((state: any) => state.payment);
  const types = new Map([['4', '請輸入買方統編'], ['2', '請輸入手機條碼'], ['1', '請輸入統一編碼']])
  const [formData, setFormData] = useState<any>({
    invoiceType: '1',
    invoiceValue: '',
    isPrintDetail: '',
  })

  const [showCode, setShowCode] = useState(false);

  const handleDataChange = (value: any, name: any) => {
    let newItem: any = {};
    if (value.hasOwnProperty('target')) value = value.target.value;
    if (name === 'invoiceType' && Number(value) === 3) {
      newItem['invoiceValue'] = '';
      setShowCode(true);
    }
    newItem[name] = value;
    setFormData({
      ...formData,
      ...newItem
    })
  }

  const fetchInvoice = async () => {
    let braId = localStorage.getItem('BRAID');
    const { orderId } = payhold;
    const { invoiceValue, invoiceType } = formData;
    await queryInvoice({
      invoiceType,
      invoiceValue,
      orderId,
      braId
    })
    history.replace(`/orderdetail?orderNo=${orderId}`)
  }

  const checkNo = (No: any) => {
    const { invoiceType } = formData;
    let cx = [1, 2, 1, 2, 1, 2, 4, 1];
    if (invoiceType !== '3' && !/[0-9]{8}/.test(No)) {
      Message.error('統編需為8位數字');
      return false;
    }
    let NoArr = [...No];
    let sum = 0;
    for (let i = 0; i < 8; i++) {
      sum += cc(NoArr[i] * cx[i]);
    }
    console.log(sum)
    if (sum % 10 === 0) {
      return true;
    } else if (NoArr[6] == 7 && ((sum + 1) % 10 == 0)) {
      return true;
    } else {
      Message.error('統編輸入有誤');
      return false;
    }
  }

  const cc = (n: any) => {
    if (n > 9) {
      let [a, b] = [...`${n}`];
      n = Number(a) + Number(b);
    }
    return n;
  }

  /* 提交 */
  const handleSubmit = () => {
    if (isEmpty(formData.invoiceValue)) {
      Message.error('請輸入載具號碼/捐贈碼');
      return false;
    } else if (formData.invoiceType !== '3' &&  formData.invoiceValue.length > 0 && !checkNo(formData.invoiceValue)) {
      return false;
    } else if (formData.invoiceType == '2' && !/^\/[0-9]{7,}$/.test(formData.invoiceValue)) {
      Message.error('手機條碼需為/+7位及以上數字');
      return false;
    } else if (formData.invoiceType == '4' && !/^[A-Z]{2}[0-9]{14}$/.test(formData.invoiceValue)) {
      Message.error('自然人憑證需為兩個大寫字母+14為數字');
      return false;
    }
    fetchInvoice();
  }

  const onChangeRadio = (value: string) => {
    setFormData({
      ...formData,
      invoiceType: value
    })
  }

  return <div className={styles.invoice_wrap}>
    <Header hasBack title="發票" />
    <div className={styles.invoice_form}>
      {<>
        {<RadioGroup onChange={onChangeRadio} value={formData.invoiceType}>
          <div className={styles.invoice_item}><Radio value={'1'} name='invoice'>紙本發票(統一編碼)</Radio></div>
          <div className={styles.invoice_item}><Radio value={'2'} name='invoice'>載具(手機條碼)</Radio></div>
          <div className={styles.invoice_item}><Radio value={'4'} name='invoice'>載具(自然人憑證)</Radio></div>
          <div className={styles.invoice_item}><Radio value={'3'} name='invoice'>捐贈碼</Radio></div>
        </RadioGroup>}
        <div className={styles.invoice_item}>
          {Number(formData.invoiceType) === 3
            ? <input
              type="text"
              className={styles.code}
              value={formData.invoiceValue}
              placeholder="請選擇捐贈碼"
              readOnly
              onClick={() => { setShowCode(true) }}
            />
            : <input
              type="text"
              className={styles.code}
              value={formData.invoiceValue}
              onChange={(e: any) => { handleDataChange(e, 'invoiceValue') }}
              placeholder={types.get(formData.invoiceType)}
            />}
        </div>
      </>}
    </div>
    <button type="button" className={styles.invoice_submit} onClick={handleSubmit}>確定</button>
    <LoveCodeModal loveVisiable={showCode} onClose={() => setShowCode(false)} onChange={(e: any) => { handleDataChange(e, 'invoiceValue') }} />
  </div>
}